package controller

import (
	"encoding/json"
	"gdfs-center/controller/ao"
	"gdfs-center/controller/vo"
	"gdfs-center/db"
	"gdfs-center/jwt"
	"gdfs-center/logcat"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"net/http"
)

//用户登录
func UserLogin(c *gin.Context) {
	c.Writer.Header().Set("content-type", "application/json")
	logcat.GetLog().Sugar().Infow("###userlogin-----------!")
	var loginvo vo.LoginVo
	var userao ao.Userlogin
	jsoner := json.Unmarshal(GetPostJson(c.Request), &userao)
	if jsoner != nil {
		WritedString(c.Writer, false, "-1", "json解析异常", nil)
		return
	}
	var user db.Admin
	log.Println("###request=", GetPostJson(c.Request))
	db.GetDB().Where("user = ?", userao.Username).First(&user)
	if user == (db.Admin{}) {
		WritedString(c.Writer, false, "1001", "用户名或密码错误", nil)
		return
	}
	//验证密码
	if user.Pass != userao.Password {
		WritedString(c.Writer, false, "1001", "用户名或密码错误", nil)
		return
	}
	//生成token
	token, err := jwt.GenerateToken(user.User, user.Pass)
	if err != nil {
		WritedString(c.Writer, false, "1001", "生成token异常", nil)
		return
	}
	loginvo.Token = token
	WritedString(c.Writer, true, "0", "登录成功", loginvo)
	return

}

func GetUserInfo(c *gin.Context) {
	c.Writer.Header().Set("content-type", "application/json")
	var userinfovo vo.UserInfoVo
	username, _ := c.Get("username")
	userinfovo.Name = username.(string)
	log.Println("##用户名:", username)
	WritedString(c.Writer, true, "0", "处理成功", userinfovo)
	return
}

func GetPostJson(r *http.Request) []byte {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(err)
	}
	return body
}
